#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include "stralloc.h"
#include "ident.h"
#include "program.h"
#include "compiler.h"

int debug_level = 7;

void preprocess(char *infile,char *outfile,
		char *define, char *include)
{
	char command[2048];
	int error;
	static char libdir[1024];

	/* build the command line */
	sprintf(command, "cpp -E -x c -C %s %s %s %s -o %s",
			include, libdir, define, infile, outfile);

	/* execute preprocessor */
	printf("Tried to execute: '%s'\n", command);
	error = system(command);
	if (error) {
		if (error > 0)
			printf("cpp exit code: %d\n", error);
		if (error < 0)
			perror("cpp failed");
	}
}

int main(int argc, char *argv[])
{
	int fd;
	program_t *prog;
	char file_name[200];
	char tmp_file_name[] = "tmpfile/macro_expanded_XXXXXX";

	if (argc != 2)
	{
		printf("Usage: a.out file\n");
		return 0;
	}

	init_strings();		/* in stralloc.c */
	init_identifiers();	/* in ident.c */
	init_locals();		/* in compiler.c */

	strcpy(file_name, argv[1]);

	fd = mkstemp(tmp_file_name);

	// preprocess
	printf("Preprocessing...\n");
	preprocess(file_name, tmp_file_name, "", "");

	// compile
	printf("Compiling...\n");
	prog = compile_file(fd, file_name);

	unlink(tmp_file_name);

	close(fd);

	printf("Done.\n");

	return 0;
}
